package dao

import (
	"context"
	"fmt"
	"github.com/aphasia51/website/internal/domain"
	"gorm.io/gorm"
)

type EquipmentDAO struct {
	db *gorm.DB
}

func NewEquipmentDap(db *gorm.DB) *EquipmentDAO {
	return &EquipmentDAO{
		db: db,
	}
}

func (dao *EquipmentDAO) Query(ctx context.Context, c domain.Equipment) ([]Equipment, error) {
	var Equipments []Equipment
	db := dao.db

	if name := c.Name; name != "" {
		name = fmt.Sprintf("%%%v%%", name)
		db = db.WithContext(ctx).Where("name like ?", name)
	}

	if storagePlace := c.StoragePlace; storagePlace != "" {
		storagePlace = fmt.Sprintf("%%%v%%", storagePlace)
		db = db.WithContext(ctx).Where("storage_place like ?", storagePlace)
	}

	// todo: fix code
	//if similarEquipment := c.SimilarEquipment; similarEquipment != "" {
	//	similarEquipment = fmt.Sprintf("%%%v%%", similarEquipment)
	//	db = db.WithContext(ctx).Where("similarEquipment like ?", similarEquipment)
	//}
	// todo: find if in hazardous_Equipment table
	//if ifHazardousEquipment := c.IfHazardousEquipment; ifHazardousEquipment != "" {
	//	ifHazardousEquipment = fmt.Sprintf("%%%v%%", ifHazardousEquipment)
	//	db = db.WithContext(ctx).Where("ifHazardousEquipment like ?", ifHazardousEquipment)
	//}
	//if c.Name == "" && c.StoragePlace == "" {
	//	return []Equipment{}, nil
	//}
	err := db.Debug().WithContext(ctx).Find(&Equipments).Error
	if err != nil {
		fmt.Println("query error")
	}
	return Equipments, nil
}

func (dao *EquipmentDAO) Select(ctx context.Context) ([]Equipment, error) {
	var Equipments []Equipment
	db := dao.db

	err := db.Debug().WithContext(ctx).Select("id", "name", "dict_name").Find(&Equipments).Error
	if err != nil {
		fmt.Println("query error")
	}
	return Equipments, nil
}

type Equipment struct {
	Id       string `gorm:"autoIncrement,primary_key"`
	Name     string `gorm:"name"`
	DictName string `gorm:"dict_name"`
	Stock    string `gorm:"stock"`
	//Classification    string `gorm:"classification"`
	//SerialNumber      string `gorm:"serial_number"`
	//Price             string `gorm:"price"`
	//StoragePlace      string `gorm:"storage_place"`
	//ManufacturingDate string `gorm:"manufacturing_date"`
}
